const config = import.meta.env;
/*
 * cs 2019-12-26
 * 格式化时间
 */
export function dateFormat(date: string | number, format: string): string {
    if (!date || !format) {
        return '';
    }
    if (typeof date != "number") {
        date = date + '';
        if (date.indexOf("T") < 0) {
            date = date.replace(/-/g, '/')
        }
    }
    const newDate: Date = new Date(new Date(date).getTime());
    let map: any = {
        M: newDate.getMonth() + 1,
        d: newDate.getDate(),
        h: parseInt(String(newDate.getHours())),
        m: newDate.getMinutes(),
        s: newDate.getSeconds(),
        q: Math.floor((newDate.getMonth() + 3) / 3),
        S: newDate.getMilliseconds() //毫秒
    };
    format = format.replace(/([yMdhmsqS])+/g, function (all: any, t: string) {
        let v = map[t];
        if (v !== undefined) {
            if (all.length > 1) {
                v = '0' + v;
                v = v.substr(v.length - 2);
            }
            return v;
        } else if (t === 'y') {
            return (newDate.getFullYear() + '').substr(4 - all.length);
        }
        return all;
    });
    return format;
}

/**
 * @param {Function} func
 * @param {number} wait
 * @param {boolean} immediate
 * @return {*}
 */
export function debounce(func: any, wait: number, immediate: boolean) {
    let timeout: any, args: any, context: any, timestamp: number, result: any

    const later = function () {
        // 据上一次触发时间间隔
        const last = +new Date() - timestamp

        // 上次被包装函数被调用时间间隔 last 小于设定时间间隔 wait
        if (last < wait && last > 0) {
            timeout = setTimeout(later, wait - last)
        } else {
            timeout = null
            // 如果设定为immediate===true，因为开始边界已经调用过了此处无需调用
            if (!immediate) {
                result = func.apply(context, args)
                if (!timeout) context = args = null
            }
        }
    }

    return function (this: any, ...args: any) {
        context = this;
        timestamp = +new Date()
        const callNow = immediate && !timeout
        // 如果延时不存在，重新设定延时
        if (!timeout) timeout = setTimeout(later, wait)
        if (callNow) {
            result = func.apply(context, args)
            context = args = null
        }

        return result
    }
}


// 首字母大小
export function titleCase(str: string): string {
    return str.replace(/( |^)[a-z]/g, L => L.toUpperCase())
}

// 下划转驼峰
export function camelCase(str: string): string {
    return str.replace(/-[a-z]/g, str1 => str1.substr(-1).toUpperCase())
}

/*
 * cs 2021-6-25
 * @prame 文件key
 * @return 文件Url
 */
export function getFileUrl(key: string): string {
    return "https://" + config.VITE_APP_BUCKETNAME + ".cos." + config.VITE_APP_STORAGEREGION + ".myqcloud.com/" +
        key;
}



/*
 * cs 2020-9-17
 * 将省 市 县转为索引 和 中文
 */
export function getAreaText(codeList: number[], allareas: any): any {
    if (typeof codeList != 'object') {
        return {};
    }
    let regions: string[] = [];
    let regionsIndex: number[] = [];
    let provinceCode: number = codeList[0];
    let provinceIndex: number = allareas.findIndex((item: any): boolean => {
        return item.id == provinceCode;
    });
    if (provinceIndex >= 0) {
        regionsIndex.push(provinceIndex);
        regions.push(allareas[provinceIndex].label);
    } else {
        return {
            indexList: regionsIndex,
            nameList: regions
        };
    }

    let cityList: Array<any> = allareas[provinceIndex].children;

    let cityCode: number = codeList[1];

    let cityIndex: number = cityList.findIndex((item: any): boolean => {
        return item.id == cityCode;
    });

    if (cityIndex >= 0) {
        regionsIndex.push(cityIndex);
        regions.push(cityList[cityIndex].label);
    } else {
        return {
            indexList: regionsIndex,
            nameList: regions
        };
    }

    let areaList: Array<any> = cityList[cityIndex].children;

    let areaCode: number = codeList[2];

    let areaIndex: number = areaList.findIndex((item: any) => {
        return item.id == areaCode;
    });

    if (areaIndex >= 0) {
        regionsIndex.push(areaIndex);
        regions.push(areaList[areaIndex].label);
    } else {
        return {
            indexList: regionsIndex,
            nameList: regions
        };
    }

    return {
        indexList: regionsIndex,
        nameList: regions
    };
}

/**
 * @author chenshuai 2020-5-19
 * @function 获取字典的字段
 * @param {string} num 比较的值
 * @param {array} obj  取值数组
 * @param {string} key 取值属性
 * @param {string} code='code' 比较值的属性
 */
export function getObjKey(num: any, obj: any, key: string, code: string = 'code'): string {
    let tampObj: any = obj.find((item: any) => {
        return item[code] == num
    })
    if (tampObj) {
        return tampObj[key] || "未知"
    } else {
        return "未知"
    }
}

/**
 * @author chenshuai 2021-11-27
 * @function 将数字转为时间字符串
 * @param num 
 * @returns 
 */
export function NumToString(num: number): string {
    if (!num) {
        return '00:00';
    }
    try {
        if (num >= 60 * 60) {
            let h = Math.floor((num / 60) * 60).toString();
            let m = Math.floor(num / 60).toString();
            let s = Math.round(num % 60).toString();
            h = h.length > 1 ? h : '0' + h;
            m = m.length > 1 ? m : '0' + m;
            s = s.length > 1 ? s : '0' + s;
            return m + ':' + s;
        } else {
            let m = Math.floor(num / 60).toString();
            let s = Math.round(num % 60).toString();
            m = m.length > 1 ? m : '0' + m;
            s = s.length > 1 ? s : '0' + s;
            return m + ':' + s;
        }
    } catch (err) {
        return '00:00';
    }
}

/*
* cs 2020-9-22
* 将"[1],[2]"的字符串 转换为 数组[1,2]
*/
export function strLabelToArr(str: string) {
    if (str) {
        str = str.replace(/\[|\]/g, "");
        let tampArr = str.split(",");
        tampArr.forEach((item: any, index: number) => {
            tampArr[index] = item;
        })
        return tampArr;
    } else {
        return [];
    }
}
